const { ccclass, property } = cc._decorator;

enum MoveDirection {
	DOWN,
	UP,
	RIGHT,
	LEFT
}

@ccclass
export default class NewClass extends cc.Component {

	@property(cc.Vec2)
	startV2: cc.Vec2 = cc.v2(1, 1);

	@property(cc.Node)
	txm: cc.Node = null;
	tiedMap:cc.TiledMap;

	mapMoveDir: MoveDirection = MoveDirection.UP;

	currentV2 = this.startV2;

	onLoad() {
		let manage=cc.director.getCollisionManager();		
		cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this._onKeyPressed, this);

		this.tiedMap=this.txm.getComponent(cc.TiledMap);
		let layer=this.tiedMap.getLayer('background');
		let t=layer.getTiledTileAt(2,18,true);
		console.log("GID:"+t.node.position);
		this.node.position=t.node.position;
	}

	start() {

	}

	update(dt) {

	}

	getTilePos(posInPixel:cc.Vec2):cc.Vec2 {
        let mapSize = this.node.getContentSize();
		let tileSize = this.tiedMap.getTileSize();
        let x = Math.floor(posInPixel.x / tileSize.width);
		let y = Math.floor((mapSize.height - posInPixel.y) / tileSize.height);
        return cc.v2(x, y);
    }

	check(v2:cc.Vec2):boolean{
		let v=this.getTilePos(v2);
		console.log("tile:"+v);
		let layer=this.tiedMap.getLayer('item');
		//console.log(layer.getTiledTileAt(1,13,false).gid);
		//console.log(layer.getTileGIDAt(v));
		return true;
	}

	move(v2: cc.Vec2) {	
		if(this.check(cc.v2(this.node.position))){

		}
		if(this.node.getNumberOfRunningActions()<=1){
			cc.tween(this.node).by(0.2, { position: cc.v3(v2) }).start();
		}
	}

	_onKeyPressed(event) {
		let tileSize=this.txm.getComponent(cc.TiledMap).getTileSize();
		let newTile: cc.Vec2 = cc.v2(0, 0);
		switch (event.keyCode) {
			case cc.macro.KEY.up:
			case cc.macro.KEY.w:
				newTile.y += tileSize.height;
				this.mapMoveDir = MoveDirection.DOWN;
				break;
			case cc.macro.KEY.down:
			case cc.macro.KEY.s:
				newTile.y -= tileSize.height;
				this.mapMoveDir = MoveDirection.UP;
				break;
			case cc.macro.KEY.left:
			case cc.macro.KEY.a:
				newTile.x -= tileSize.width;
				this.mapMoveDir = MoveDirection.RIGHT;
				break;
			case cc.macro.KEY.right:
			case cc.macro.KEY.d:
				newTile.x += tileSize.width;
				this.mapMoveDir = MoveDirection.LEFT;
				break;
			default:
				return;
		}
		this.move(newTile);
	}
}
